import 'package:flame/components.dart';
import 'package:flutter_flame/component/SpriteEntity.dart';
import 'package:flutter_flame/worlds/game/audio/SoundManager.dart';

import '../../../../config/AssetsName.dart';
import '../../entity/ZombieStateEnumType.dart';
import '../../model/PlantModel.dart';
import '../NormalZombie.dart';
import '../PeaHit.dart';

// 植物子弹
abstract class Bullet extends SpriteEntity {
  PlantModel plantModel;
  final PeaHit peaHit = PeaHit(AssetsName.spritePeaHit);
  final NormalZombie? targetZombie;

  Bullet(
    super.spriteAsset, {
    required Vector2 position,
    required this.plantModel,
    this.targetZombie,
  }) {
    this.position = position;
    size = Vector2(22, 22);
  }

  @override
  Future<void> onLoad() async {
    await super.onLoad();
    addHitBox();
    priority = bulletPriority;
  }

  @override
  void update(double dt) {
    position.x += plantModel.bulletSpeedHorizontal! * dt;
    if (position.x > game.size.x) {
      removeFromParent();
    }
  }

  @override
  void onCollision(Set<Vector2> intersectionPoints, PositionComponent other) {
    super.onCollision(intersectionPoints, other);
    // 击中僵尸
    if (other is NormalZombie) {
      if (targetZombie == null ||
          (targetZombie != null && targetZombie == other)) {
        SoundManager().playRandomPeaHitSound();
        other.healthBar?.currentHealth -= plantModel.attack;
        if (other.healthBar!.currentHealth <= 0 &&
            other.state != ZombieStateEnumType.dying) {
          other.died();
        }
        if (other.state != ZombieStateEnumType.dying) {
          // 豌豆碰撞效果
          other.add(peaHit);
          Future.delayed(Duration(milliseconds: 200), () {
            peaHit.removeFromParent();
          });
          // 僵尸被击中亮一下
          other.underAttack();
        }
        removeFromParent();
      }
    }
  }
}
